let username = ''; // Will be set from session
let udpSocket = null;
let tcpSocket = null;

// Initialize WebSocket connection
function initWebSocket() {
    sendOnlineNotification();
    loadContacts();
    checkOfflineMessages();
}

function sendOnlineNotification() {
    const message = {
        type: 'online',
        username: username,
        timestamp: new Date().getTime()
    };
    console.log('Online notification sent:', message);
}

function loadContacts() {
    fetch('/get_contacts')
        .then(response => response.json())
        .then(data => {
            const contactList = document.getElementById('contact-list');
            contactList.innerHTML = '';
            
            data.all.forEach(user => {
                const li = document.createElement('li');
                li.textContent = user;
                if (data.online.includes(user)) {
                    li.classList.add('online');
                } else {
                    li.classList.add('offline');
                }
                li.onclick = () => startChat(user);
                contactList.appendChild(li);
            });
        });
}

function startChat(contact) {
    console.log('Starting chat with:', contact);
    // Clear previous messages and load chat history
    document.getElementById('message-area').innerHTML = '';
    // Additional implementation needed for loading chat history
}

function sendMessage() {
    const input = document.getElementById('message-input');
    const message = input.value;
    if (!message) return;
    
    const to = 'user2'; // Should be selected from UI
    
    const msg = {
        type: 'message',
        from: username,
        to: to,
        content: message,
        timestamp: new Date().getTime()
    };
    
    fetch('/send_message', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(msg)
    })
    .then(response => response.json())
    .then(data => {
        console.log('Message sent:', data);
        input.value = '';
        displayMessage(msg);
    });
}

function sendFile() {
    const fileInput = document.getElementById('file-input');
    const file = fileInput.files[0];
    if (!file) return;
    
    const formData = new FormData();
    formData.append('file', file);
    
    fetch('/send_file', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('File sent:', data);
        fileInput.value = '';
        // Display file message in chat
        displayMessage({
            from: username,
            content: `[File: ${file.name}]`,
            timestamp: new Date().getTime()
        });
    });
}

function displayMessage(msg) {
    const messageArea = document.getElementById('message-area');
    const div = document.createElement('div');
    div.innerHTML = `<strong>${msg.from}</strong>: ${msg.content}`;
    messageArea.appendChild(div);
    messageArea.scrollTop = messageArea.scrollHeight;
}

function checkOfflineMessages() {
    console.log('Checking for offline messages...');
    // Implementation to fetch and display offline messages
}

// Initialize when page loads
window.onload = function() {
    // Get username from session (needs backend implementation)
    fetch('/get_username')
        .then(response => response.json())
        .then(data => {
            username = data.username;
            initWebSocket();
        });
    
    // Set up periodic contact list refresh
    setInterval(loadContacts, 30000);
};
